package com.zyzd.general.module.change_app_name;

import android.content.ComponentName;
import android.content.pm.PackageManager;
import android.support.v4.app.Fragment;

import com.zyzd.commontools.AppContext;
import com.zyzd.commontools.utils.SystemUtil;
import com.zyzd.general.R;
import com.zyzd.retrofit.base.BaseFragment;

import butterknife.OnClick;

/**
 * Created by lzy on 2018/11/2 0002.
 * description ${
 * 动态修改app名和icon
 *
 * 暂时发现问题：没有恢复默认，会导致新包部署时无法安装
 *
 * 但是在release版本安装时可以正常
 * }
 */
public class ChangeAppNameFragment extends BaseFragment {

    private PackageManager mPackageManager;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_change_app_name;
    }

    @Override
    protected void initData() {
        mPackageManager = getContext().getPackageManager();
    }

    @OnClick(R.id.btn_change_app_name)
    public void onClick() {
        updateIcon();
    }

    //检查图标并更换
    public void updateIcon() {
        //获取当前的ComponentName
        ComponentName currentName = getActivity().getComponentName();
        if (currentName.getClassName().equals(SystemUtil.getPackageName() + ".china")) {
            ComponentName defaultComponent = new ComponentName(AppContext.getContext(), SystemUtil.getPackageName() + ".MainActivity");
            disableComponent(currentName);
            enableComponent(defaultComponent);
        } else {
            ComponentName china = new ComponentName(AppContext.getContext(), SystemUtil.getPackageName() + ".china");
            disableComponent(currentName);
            enableComponent(china);
        }
    }

    //启用组件
    public void enableComponent(ComponentName componentName) {
        mPackageManager.setComponentEnabledSetting(componentName,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
    }

    //隐藏组件
    public void disableComponent(ComponentName componentName) {
        mPackageManager.setComponentEnabledSetting(componentName,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
    }

    public static Fragment getInstance() {
        return new ChangeAppNameFragment();
    }
}
